//
// Created by Martin on 2021/10/2.
//

#include "FlyweightFactory.h"
#include "ConcreteFlyweight.h"
#include <iostream>

using namespace std;

// 类的静态成员定义
// 共享的内存池
std::unordered_map<std::string, Flyweight*> FlyweightFactory::pool;

/**
 * 享元工厂
 * @note 如果内存池中存在指定字符串, 就直接取出其对应的享元对象; 如果不存在, 就创建一个享元对象并加入内存池, 并返还给调用者.
 * 这里字符串用来标识享元对象.
 * @param extrinsic 标识享元对象的外部状态
 * @return
 */
Flyweight* FlyweightFactory::getFlyweight(std::string& extrinsic)
{
    Flyweight *flyweight = nullptr;

    if (pool.find(extrinsic) != pool.end()) {
        flyweight = pool[extrinsic];
        cout << "已有" << extrinsic << " 直接从池中取---->" << flush;
    }
    else {
        // 如果池中不存在, 就根据外部状态创建享元对象
        flyweight = new ConcreteFlyweight(extrinsic);
        // 放入池中
        pool[extrinsic] = flyweight;

        cout << "创建 " << extrinsic << " 并从池中取出---->" << flush;
    }

    return flyweight;
}
